const chatWindow = document.querySelector('.chat-window');
const chatHeader = document.querySelector('.chat-header');
const chatBody = document.querySelector('.chat-body');
const chatFooter = document.querySelector('.chat-footer');
const messageInput = document.querySelector('input[type="text"]');
const sendButton = document.querySelector('input[type="submit"]');
const addressModal = document.querySelector('#addressModal');
const addressInput = document.querySelector('#addressInput');
let ws = null;
let address = '127.0.0.1'; // 初始服务器IP地址
let server_address = address; // 初始ws服务器地址

function createWebSocket() {
  ws = new WebSocket(`ws://${server_address}:2023/`);
  // 监听WebSocket连接事件
  ws.addEventListener('open', (event) => {
    console.log('客户端 已连接');
  });

  // 监听WebSocket消息事件
  ws.addEventListener('message', (event) => {
    const message = JSON.parse(event.data);
    if (message.type === 'message') {
      const content = message.content;
  
      const messageWindow = document.createElement('div');
      messageWindow.className = 'message-window';
      const messageElement = document.createElement('div');
      messageElement.className = 'message';
  
      messageElement.innerHTML = `
        <div class="avatar"></div>
        <div class="content">${parseMessageContent(content)}</div>
      `;
  
      const deleteButton = document.createElement('button');
      deleteButton.className = 'text-neutral-300 transition hover:text-neutral-900 dark:text-neutral-600 dark:hover:text-neutral-300';
      deleteButton.style.border = 'none';
      deleteButton.style['background-color'] = 'transparent';
      deleteButton.style.fontSize = '6px';
      deleteButton.style.float = 'right';
      deleteButton.style.cursor = 'pointer';
      deleteButton.style['margin-bottom'] = '1px';
      deleteButton.title = '删除';
      deleteButton.innerHTML = '<svg t="1687940513319" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3173" width="13" height="13"><path d="M202.666667 256h-42.666667a32 32 0 0 1 0-64h704a32 32 0 0 1 0 64H266.666667v565.333333a53.333333 53.333333 0 0 0 53.333333 53.333334h384a53.333333 53.333333 0 0 0 53.333333-53.333334V352a32 32 0 0 1 64 0v469.333333c0 64.8-52.533333 117.333333-117.333333 117.333334H320c-64.8 0-117.333333-52.533333-117.333333-117.333334V256z m224-106.666667a32 32 0 0 1 0-64h170.666666a32 32 0 0 1 0 64H426.666667z m-32 288a32 32 0 0 1 64 0v256a32 32 0 0 1-64 0V437.333333z m170.666666 0a32 32 0 0 1 64 0v256a32 32 0 0 1-64 0V437.333333z" fill="#000000" p-id="3174"></path></svg>'; 
      const confirmDialog = document.getElementById('confirmDialog');
      const confirmYes = document.getElementById('confirmYes');
      const confirmNo = document.getElementById('confirmNo');
      deleteButton.onclick = function() {
        confirmDialog.classList.remove('hidden');
      };

      confirmYes.onclick = function() {
        deleteButton.parentNode.remove();
        confirmDialog.classList.add('hidden');
      };

      confirmNo.onclick = function() {
        confirmDialog.classList.add('hidden');
      };
  
      const copyButton = document.createElement('button');
      copyButton.className = 'text-neutral-300 transition hover:text-neutral-900 dark:text-neutral-600 dark:hover:text-neutral-300';
      copyButton.style.border = 'none';
      copyButton.style['background-color'] = 'transparent';
      copyButton.style.fontSize = '6px';
      copyButton.style.float = 'right';
      copyButton.style.cursor = 'pointer';
      copyButton.style['margin-bottom'] = '1px';
      copyButton.title = '复制';
      copyButton.innerHTML = '<svg t="1687940444536" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2130" width="12" height="12"><path d="M720 192h-544A80.096 80.096 0 0 0 96 272v608C96 924.128 131.904 960 176 960h544c44.128 0 80-35.872 80-80v-608C800 227.904 764.128 192 720 192z m16 688c0 8.8-7.2 16-16 16h-544a16 16 0 0 1-16-16v-608a16 16 0 0 1 16-16h544a16 16 0 0 1 16 16v608z" p-id="2131"></path><path d="M848 64h-544a32 32 0 0 0 0 64h544a16 16 0 0 1 16 16v608a32 32 0 1 0 64 0v-608C928 99.904 892.128 64 848 64z" p-id="2132"></path><path d="M608 360H288a32 32 0 0 0 0 64h320a32 32 0 1 0 0-64zM608 520H288a32 32 0 1 0 0 64h320a32 32 0 1 0 0-64zM480 678.656H288a32 32 0 1 0 0 64h192a32 32 0 1 0 0-64z" p-id="2133"></path></svg>';
      copyButton.onclick = function() {
        navigator.clipboard.writeText(content);
        showNotification('<div style="display: flex; align-items: center;"><span style="background-color: green; color: white; border-radius: 50%; width: 18px; height: 18px; display: flex; align-items: center; justify-content: center; text-align: center; font-size: 12px; line-height: 12px;">&#10004;</span>&nbsp;&nbsp;<span style="font-size: 12px; line-height: 12px;">复制成功</span></div>', 'info');
      };
  
      messageWindow.appendChild(messageElement);
      messageWindow.appendChild(deleteButton);
      messageWindow.appendChild(copyButton);
      chatBody.appendChild(messageWindow);
      chatBody.scrollTop = chatBody.scrollHeight;
    }
  });
}

function sendMessage(event) {
  event.preventDefault();
  const message = messageInput.value;
  if (message.trim()) {
    ws.send(JSON.stringify({
      type: 'message',
      content: message.toString()
    }));
    const messageWindow = document.createElement('div');
    messageWindow.className = 'message-window';
    const messageElement = document.createElement('div');
    messageElement.className = 'message sent';
    messageElement.innerHTML = `
      <div class="content">${parseMessageContent(message)}</div>
      <div class="avatar"></div>
    `;
    const deleteButton = document.createElement('button');
    deleteButton.className = 'text-neutral-300 transition hover:text-neutral-900 dark:text-neutral-600 dark:hover:text-neutral-300';
    deleteButton.style.border = 'none';
    deleteButton.style['background-color'] = 'transparent';
    deleteButton.style.fontSize = '6px';
    deleteButton.style.float = 'right';
    deleteButton.style.cursor = 'pointer';
    deleteButton.style['margin-bottom'] = '1px';
    deleteButton.title = '删除';
    deleteButton.innerHTML = '<svg t="1687940513319" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3173" width="13" height="13"><path d="M202.666667 256h-42.666667a32 32 0 0 1 0-64h704a32 32 0 0 1 0 64H266.666667v565.333333a53.333333 53.333333 0 0 0 53.333333 53.333334h384a53.333333 53.333333 0 0 0 53.333333-53.333334V352a32 32 0 0 1 64 0v469.333333c0 64.8-52.533333 117.333333-117.333333 117.333334H320c-64.8 0-117.333333-52.533333-117.333333-117.333334V256z m224-106.666667a32 32 0 0 1 0-64h170.666666a32 32 0 0 1 0 64H426.666667z m-32 288a32 32 0 0 1 64 0v256a32 32 0 0 1-64 0V437.333333z m170.666666 0a32 32 0 0 1 64 0v256a32 32 0 0 1-64 0V437.333333z" fill="#000000" p-id="3174"></path></svg>';
    const confirmDialog = document.getElementById('confirmDialog');
    const confirmYes = document.getElementById('confirmYes');
    const confirmNo = document.getElementById('confirmNo');
    deleteButton.onclick = function() {
      confirmDialog.classList.remove('hidden');
    };

    confirmYes.onclick = function() {
      deleteButton.parentNode.remove();
      confirmDialog.classList.add('hidden');
    };

    confirmNo.onclick = function() {
      confirmDialog.classList.add('hidden');
    };

    const copyButton = document.createElement('button');
    copyButton.className = 'text-neutral-300 transition hover:text-neutral-900 dark:text-neutral-600 dark:hover:text-neutral-300';
    copyButton.style.border = 'none';
    copyButton.style['background-color'] = 'transparent';
    copyButton.style.fontSize = '6px';
    copyButton.style.float = 'right';
    copyButton.style.cursor = 'pointer';
    copyButton.style['margin-bottom'] = '1px';
    copyButton.title = '复制';
    copyButton.innerHTML = '<svg t="1687940444536" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2130" width="12" height="12"><path d="M720 192h-544A80.096 80.096 0 0 0 96 272v608C96 924.128 131.904 960 176 960h544c44.128 0 80-35.872 80-80v-608C800 227.904 764.128 192 720 192z m16 688c0 8.8-7.2 16-16 16h-544a16 16 0 0 1-16-16v-608a16 16 0 0 1 16-16h544a16 16 0 0 1 16 16v608z" p-id="2131"></path><path d="M848 64h-544a32 32 0 0 0 0 64h544a16 16 0 0 1 16 16v608a32 32 0 1 0 64 0v-608C928 99.904 892.128 64 848 64z" p-id="2132"></path><path d="M608 360H288a32 32 0 0 0 0 64h320a32 32 0 1 0 0-64zM608 520H288a32 32 0 1 0 0 64h320a32 32 0 1 0 0-64zM480 678.656H288a32 32 0 1 0 0 64h192a32 32 0 1 0 0-64z" p-id="2133"></path></svg>';
    copyButton.onclick = function() {
      navigator.clipboard.writeText(message);
      showNotification('<div style="display: flex; align-items: center;"><span style="background-color: green; color: white; border-radius: 50%; width: 18px; height: 18px; display: flex; align-items: center; justify-content: center; text-align: center; font-size: 12px; line-height: 12px;">&#10004;</span>&nbsp;&nbsp;<span style="font-size: 12px; line-height: 12px;">复制成功</span></div>', 'info');
    };
    messageWindow.appendChild(messageElement);
    messageWindow.appendChild(deleteButton);
    messageWindow.appendChild(copyButton);
    chatBody.appendChild(messageWindow);
    chatBody.scrollTop = chatBody.scrollHeight;
    messageInput.value = '';
  }
}

function showNotification(message, type) {
  const notification = document.createElement('div');
  notification.className = `notification ${type}`;
  notification.style.display = 'flex';
  notification.style.alignItems = 'center';
  notification.style.justifyContent = 'center';
  notification.innerHTML = `<div class="notification-content">${message}</div>`;

  // 获取 .chat-header 元素的位置和尺寸
  const chatHeader = document.querySelector('.chat-header');
  const { height } = chatHeader.getBoundingClientRect();

  // 计算悬浮通知应该放置的位置
  notification.style.position = 'absolute';
  notification.style.top = `${height / 2}px`;

  document.body.appendChild(notification);
  setTimeout(() => {
    notification.remove();
  }, 3000);
}

function parseMessageContent(content) {
  // 替换特殊字符
  content = content.replace(/</g, '&lt;').replace(/>/g, '&gt;');
  // 解析链接
  if (window.utools) {
    content = content.replace(/(https?:\/\/[^\s]+)/g, (match, url) => {
      return `<a href="#" onclick="utools.shellOpenExternal('${url}');">${url}</a>`;
    });
  } else {
    content = content.replace(/(https?:\/\/[^\s]+)/g, '<a href="$1" target="_blank">$1</a>');
  }
  // 处理换行
  content = content.replace(/\n/g, '<br/>');
  return content;
}

sendButton.addEventListener('click', sendMessage);
messageInput.addEventListener('keydown', function(event) {
  if (event.key === 'Enter') {
    sendMessage(event);
  }
});

// 监听设置按钮
function toggleSettingsPanel() {
  const settingsPanel = document.getElementById('settingsPanel');
  settingsPanel.classList.toggle('active');
}

// 监听黑夜按钮
 function toggleDarkMode() {
  chatWindow.classList.add('dark-mode');
  chatHeader.classList.add('dark-mode');
  chatBody.classList.add('dark-mode');
  chatFooter.classList.add('dark-mode');
}

// 监听白天按钮
function toggleDayMode() {
  chatWindow.classList.remove('dark-mode');
  chatHeader.classList.remove('dark-mode');
  chatBody.classList.remove('dark-mode');
  chatFooter.classList.remove('dark-mode');
}

// 监听获取安卓版本按钮
 function openAndroidApk() {
  utools.shellOpenExternal('https://www.aliyundrive.com/s/S6Utz8VNA5U')
 }

// 打开服务器地址模态框
function openAddressModal() {
  addressInput.value = server_address; // 只显示IP地址
  addressModal.classList.add('active');
}

// 保存服务器地址
function saveAddress() {
  const newAddress = addressInput.value.trim();
  if (validateIPAddress(newAddress) && !startsWith255(newAddress)) {
    ws.close(); // 先关闭旧的WebSocket连接
    server_address = newAddress; // 更新地址变量
    createWebSocket(); // 创建新的WebSocket连接
    addressModal.classList.remove('active'); // 关闭模态框
  } else {
    addressInput.style.borderColor = 'red'; // 设置边框颜色为红色
    addressInput.classList.add('shake'); // 添加震动效果
    setTimeout(() => {
      addressInput.classList.remove('shake'); // 移除震动效果
    }, 500);
  }
}

// 关闭服务器地址模态框
function closeAddressModal() {
  addressModal.classList.remove('active');
}

// 校验IP地址的格式是否合法
function validateIPAddress(ip) {
  const ipRegex = /^(25[0-4]|2[0-4]\d|1\d{2}|[1-9]\d|\d)(\.(25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)){3}$/;
  return ipRegex.test(ip);
}

// 判断IP地址是否以255开头
function startsWith255(ip) {
  const ipParts = ip.split('.');
  return ipParts[0] === '255';
}

// 监听输入框的输入事件，重置边框颜色
addressInput.addEventListener('input', function() {
  addressInput.style.borderColor = '';
});

// 创建初始的WebSocket连接
createWebSocket();